package notes.java.java8.demo.streams;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/** 排序*/
public class S6_Sorted {

	public static void main(String[] args) {
		
		// 测试数据
		List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e"));
		
		// 倒序
		List<String> list2 = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
		
		// 输出 倒序
		list2.forEach(System.out::println);
		
		// 测试数据
		List<Student> students = new ArrayList<>();
		Student stu = new Student();
		stu.setName("晓丽");
		stu.setAge(26);
		students.add(stu);
		
		Student stu2 = new Student();
		stu2.setName("王五");
		stu2.setAge(22);
		students.add(stu2);
		
		Student stu3 = new Student();
		stu3.setName("小爱");
		stu3.setAge(33);
		students.add(stu3);
		
		// 根据年龄排序正序
		List<Student> ss = students.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
		ss.forEach(s->{
			System.out.println(s.getName() + "\t" + s.getAge());
		});
		
		System.out.println("--------------");
		
		// 根据年龄排序倒序
		ss = students.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
		ss.forEach(s->{
			System.out.println(s.getName() + "\t" + s.getAge());
		});
		
		// list map 排序
		List<Map<String, String>> listMap = new ArrayList<>();
		// 测试数据
		Map<String, String> m1 = new HashMap<>();
		m1.put("name", "zhangsan");
		m1.put("age", "36");
		listMap.add(m1);
		Map<String, String> m2 = new HashMap<>();
		m2.put("name", "lisi");
		m2.put("age", "28");
		listMap.add(m2);
		Map<String, String> m3 = new HashMap<>();
		m3.put("name", "wangwu");
		m3.put("age", "33");
		listMap.add(m3);
		
		// 根据年龄倒序
		List<Map<String, String>> newListMap = listMap.stream().sorted(Comparator.comparing(S6_Sorted::compareByAge).reversed()).collect(Collectors.toList());
		
		// 输出
		System.out.println("------------");
		newListMap.forEach(map-> {
			System.out.println(map.get("name") + "\t" + map.get("age"));
		});
	}
	
	// 根据年龄排序
	private static Integer compareByAge(Map<String, String> map) {
		return Integer.valueOf(map.get("age"));
	}
}

class Student {
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}
